const multer = require('multer')
const fs = require('fs/promises');
const dir_multy = 'tmp/my-uploads'

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, dir_multy)
  },
  filename: function (req, file, cb) {
    // 根据file.originalname的后缀名来设置文件名
    if (file.originalname.match(/\.([^\.]*)$/))
      cb(null, Math.floor(Math.random() * 1E9) + file.originalname.match(/\.([^\.]*)$/)[0])
    else
      cb(null, Math.floor(Math.random() * 1E9) + '.unknown')
  },
})

const limit_multy = {
  fileSize: 1024 * 1024 * 1024,
  // 限制50个文件以内
  files: 50
}

const upload_multy = multer({ storage: storage, limits: limit_multy })


const storage_chunk = multer.diskStorage({
  destination: function (req, file, cb) {
    let path = dir_multy + '/' + req.body.filename 
    console.log(path)
    fs.mkdir(path)
    cb(null, path)
  },
  filename: function (req, file, cb) {
    // 切片，没有后缀什么的
    cb(null, req.body.index + '')

  },
})

const limit_chunk = {
  fileSize: 10 * 1024 * 1024,
}

const upload_chunk = multer({ storage, limits: limit_chunk })

module.exports = { upload_multy, dir_multy, upload_chunk }